package dao;

import model.GenericModel;
import model.Usuario;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class GenericDao {

	protected static Session session = null;
	protected static Transaction transaction = null;

	public boolean inserir(GenericModel entidade) {
		boolean retorno = false;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			session.save(entidade);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
			retorno = true;
		}
		return retorno;
	}

	public boolean alterar(GenericModel entidade) {
		boolean retorno = false;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			session.update(entidade);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
			retorno = true;
		}
		System.out.println("Salvou: " + ((Usuario)entidade).getNome());
		return retorno;
	}

	public boolean remover(GenericModel entidade) {
		boolean retorno = false;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			System.out.println("Deletando " + ((Usuario)entidade).getNome());
			session.delete(entidade);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
			retorno = true;
		}
		return retorno;
	}
}